//编写读端，反序列化打印
#include <google/protobuf/message.h>
#include <iostream>
#include <fstream>
#include"contacts.pb.h"

using namespace std;

void PrintContacts(const ccontacts2::Contacts& contacts)
{
    for(int j = 0; j < contacts.people_size(); j++)
    {
        const ccontacts2::PeopleInfo& people = contacts.people(j);
        cout << "------------联系人" << j+1 << "------------" << endl;
        cout << "联系人姓名： " << people.name() << endl;
        cout << "联系人年龄： " << people.age() << endl;
        for(int i = 0;i < people.phone_numbers_size();i++)
        {
            const ccontacts2::PeopleInfo_Phone& phone = people.phone_numbers(i);
            cout << "phone number" << i+1 << ":" << phone.number() << endl;
        }
        

        //打印未知字段
        const google::protobuf::Reflection* reflection = ccontacts2::PeopleInfo::GetReflection();
        const google::protobuf::UnknownFieldSet& unknown_set = reflection->GetUnknownFields(people);
        for(int i = 0; i < unknown_set.field_count(); i++)
        {
            const google::protobuf::UnknownField& unknown_field = unknown_set.field(i);
            cout << "未知字段" << i+1 << ":" 
                 << "  编号：" << unknown_field.number()
                 << "  类型：" << unknown_field.type();
            switch(unknown_field.type())
            {
                case google::protobuf::UnknownField::TYPE_VARINT:
                    cout << "  值：" << unknown_field.varint() << endl;
                    break;
                case google::protobuf::UnknownField::TYPE_FIXED32:
                    cout << "  值：" << unknown_field.fixed32() << endl;                    
                    break;
                case google::protobuf::UnknownField::TYPE_FIXED64:
                    cout << "  值：" << unknown_field.fixed64() << endl;
                    break;
                case google::protobuf::UnknownField::TYPE_LENGTH_DELIMITED:
                    cout << "  值：" << unknown_field.length_delimited() << endl;
                    break;
                default:
                    cout << "  值：未知类型" << endl;
                    break;
                //case ...
            }
        }
        cout << endl;
    }
}

int main()
{
    ccontacts2::Contacts contacts;
    //1.读取本地已存在文件
    fstream in("../contacts.bin",ios::in | ios::binary);
    if(!contacts.ParseFromIstream(&in))
    {
        cout << "解析失败" << endl;
        return -1;
    }
    //2.打印通讯录表
    PrintContacts(contacts);

    //3.关闭文件
    in.close();
    return 0;
}
